package com.beijiteshop.shop.ui.account.fragment

import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.shop.R
import com.beijiteshop.shop.base.BaseContainerFragment
import com.beijiteshop.shop.databinding.FragmentBindPhoneBinding
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.login.vm.UserVM
import com.blankj.utilcode.util.LogUtils
import org.koin.android.viewmodel.ext.android.viewModel

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/26 11:39
 * @Description 绑定/解绑手机
 */
class BindPhoneFragment : BaseContainerFragment(R.layout.fragment_bind_phone) {

    companion object{

        const val TYPE_BIND = "type_bind"

        /**
         * @param bind true: 绑定手机 false: 更换手机
         */
        fun newInstance(bind: Boolean): BindPhoneFragment{
            return BindPhoneFragment().apply {
                arguments = Bundle().apply {
                    putBoolean(TYPE_BIND,bind)
                }
            }
        }
    }

    private val mBinding by bindView<FragmentBindPhoneBinding>()
    private val mUserVM: UserVM by viewModel()

    private var mCountDownTimer: CountDownTimer? = null
    private var mIsCountDown = false
    private var mPhoneStr: String? = null
    private var mCodeStr: String? = null

    /**
     * 是否是绑定手机
     */
    private var mIsBind = true

    override fun onLazyLoad() {

    }

    override fun initView(view: View) {
        mIsBind = arguments?.getBoolean(TYPE_BIND)?: false
        mBinding.bindPhoneTitleTv.text = if (mIsBind) {
            resources.getString(R.string.please_input_phone_num)
        } else {
            resources.getString(R.string.please_input_original_phone)
        }
        mBinding.bindPhoneSafetyPromptTv.text = if (mIsBind) {
            resources.getString(R.string.bind_phone_safety_prompt)
        } else {
            resources.getString(R.string.rebind_phone_safety_prompt)
        }

        setCodeBtnEnable()
        setLoginBtnEnable()
    }

    override fun initData() {

    }

    override fun initEvent() {

        startObserve()

        mBinding.bindPhoneTitleBar.titleBarBackIv.setOnClickListener {
            close()
        }

        mBinding.bindPhoneEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                setLoginBtnEnable()
                setCodeBtnEnable()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        mBinding.bindPhoneCodeEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                setLoginBtnEnable()
                setCodeBtnEnable()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })

        mBinding.bindPhoneGetCodeBtn.setOnClickListener {
            if (!mPhoneStr.isNullOrEmpty()){
                showLoading()
                mUserVM.getSmsCode(mPhoneStr!!)
            }
        }

        mBinding.bindPhoneBindBtn.setOnClickListener {
            if (mPhoneStr.isNullOrEmpty() || mCodeStr.isNullOrEmpty()){
                showToast(resources.getString(R.string.please_input_phone_and_code))
            }else{
                showLoading(resources.getString(R.string.binding))
                mUserVM.bindPhone(mPhoneStr!!,mCodeStr!!)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mCountDownTimer?.cancel()
    }

    private fun startObserve(){
        mUserVM.liveSmsCode.observeKt {
            hideLoading()
            showToast(resources.getString(R.string.verification_code_sent))
            startCountDown()
        }

        mUserVM.liveBindPhone.observeKt { token ->
            hideLoading()
            showToast(resources.getString(R.string.bind_success))
            EventUtil.post(EventKey.ACCOUNT_BIND_SUCCESS)
            close()
        }

        mUserVM.liveNetError.observeKt {
            hideLoading()
            showToast(it?:resources.getString(R.string.state_network_error))
        }
        mUserVM.liveError.observeKt {
            hideLoading()
            showToast(it?:resources.getString(R.string.something_error))
        }
    }

    private fun startCountDown(){
        if (mCountDownTimer == null){
            mCountDownTimer = object : CountDownTimer(60*1000,1000){
                override fun onFinish() {
                    mIsCountDown = false
                    mBinding.bindPhoneGetCodeBtn.text = resources.getString(R.string.get_verification_code)
                    setCodeBtnEnable()
                }

                override fun onTick(millisUntilFinished: Long) {
                    mIsCountDown = true
                    mBinding.bindPhoneGetCodeBtn.isEnabled = false
                    mBinding.bindPhoneGetCodeBtn.text = "${(millisUntilFinished/1000f).toInt()}s"
                }
            }
        }
        mCountDownTimer?.start()
    }

    private fun setLoginBtnEnable(){
        mPhoneStr = mBinding.bindPhoneEt.text?.toString()
        mCodeStr = mBinding.bindPhoneCodeEt.text?.toString()
        mBinding.bindPhoneBindBtn.isEnabled = !mPhoneStr.isNullOrEmpty() && !mCodeStr.isNullOrEmpty()
    }

    private fun setCodeBtnEnable(){
        mPhoneStr = mBinding.bindPhoneEt.text?.toString()
        mBinding.bindPhoneGetCodeBtn.isEnabled = !mPhoneStr.isNullOrEmpty() && !mIsCountDown
    }
}